<?php

namespace common\models\system;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%admin}}".
 *
 * @property int $uid 用户ID
 * @property string $username 用户名
 * @property string $password 密码
 * @property string $salt 密码干扰字符
 * @property string $email 用户邮箱
 * @property string $mobile 用户手机
 * @property int $reg_time 注册时间
 * @property int $reg_ip 注册IP
 * @property int $last_login_time 最后登录时间
 * @property int $last_login_ip 最后登录IP
 * @property int $updated_at 更新时间
 * @property int $status 用户状态 1正常 0禁用
 * @property string $nickname 昵称
 */
class Admin extends \common\core\BaseActiveRecord implements IdentityInterface
{
    public $role;

    //状态
    const STATUS_禁用 = 0;
    const STATUS_正常  = 1;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'reg_time',
                'updatedAtAttribute' => 'updated_at',
                'value' => time(),
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['username', 'password', 'salt', 'email'], 'required'],
            [['reg_time', 'last_login_time', 'last_login_ip', 'updated_at', 'status'], 'integer'],
            [['username'], 'string', 'max' => 16],
            [['password'], 'string', 'max' => 60],
            [['salt', 'email'], 'string', 'max' => 32],
            [['mobile'], 'string', 'max' => 15],
            [['nickname'], 'string', 'max' => 50],
            [['reg_ip'], 'string', 'max' => 20],
            [['username'], 'unique'],
            [['email'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'uid' => '用户ID',
            'username' => '用户名',
            'password' => '密码',
            'salt' => '密码干扰字符',
            'email' => '用户邮箱',
            'mobile' => '用户手机',
            'reg_time' => '注册时间',
            'reg_ip' => '注册IP',
            'last_login_time' => '最后登录时间',
            'last_login_ip' => '最后登录IP',
            'updated_at' => '更新时间',
            'status' => '用户状态',
            'nickname' => '昵称',
        ];
    }

    /**
     * 根据UID获取账号信息
     */
    public static function findIdentity($uid)
    {
        return static::findOne(['uid' => $uid, 'status' => self::STATUS_正常]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * 根据用户名获取账号信息
     *
     * @param string $username
     * @return \backend\models\Admin|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_正常]);
    }

    /**
     * 根据用户名获取账号信息
     *
     * @param string $username
     * @return \backend\models\Admin|null
     */
    public static function findByUserId($id)
    {
        return static::findOne(['uid' => $id]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password' => $token,
            'status' => self::STATUS_正常,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->salt;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * 验证密码
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * 设置加密后的密码
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * 设置密码干扰码
     */
    public function generateAuthKey()
    {
        $this->salt = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password = null;
    }

    /**
     * 状态字典
     * @param null $index
     * @return array|mixed
     */
    public static function getStatus($index = null) {
        $map = [
            self::STATUS_禁用 => '禁用',
            self::STATUS_正常 => '正常',
        ];

        return ($index === null) ? $map : (isset($map[$index]) ? $map[$index] : '未知');
    }

    /**
     * 角色
     *
     * @return \yii\rbac\Item[]|\yii\rbac\Role[]
     */
    public static function roleList()
    {
        $list = [];
        $DbManager = new \common\core\rbac\DbManager();
        $roles = $DbManager->getRoles();
        if ($roles) {
            foreach ($roles as $role) {
                $list[$role->name] = $role->name;
            }
        }
        return $list;
    }

    /**
     * 关联角色分配表
     * @return $this
     */
    public function getAuthAssignment()
    {
        return $this->hasMany(AuthAssignment::className(), ['user_id' => 'uid']);
    }
}
